<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="clearfix">
          <span>{{ isEdit ? '编辑分类' : '新增分类' }}</span>
        </div>
      </template>

      <el-form
        ref="categoryFormRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        style="max-width: 600px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入分类名称" />
        </el-form-item>
        
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            placeholder="请输入描述"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="goBack">返回</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getCategoryById, saveOrUpdateCategory } from '@/api/articleCategory'

// 路由相关
const route = useRoute()
const router = useRouter()

// 表单引用
const categoryFormRef = ref()

// 是否为编辑模式
const isEdit = ref(false)

// 表单数据
const form = reactive({
  id: undefined,
  name: '',
  description: ''
})

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }]
}

// 获取分类详情
const getCategoryDetail = async (id) => {
  try {
    const response = await getCategoryById(id)
    Object.assign(form, response.data)
  } catch (error) {
    ElMessage.error('获取分类信息失败')
  }
}

// 提交表单
const submitForm = async () => {
  if (!categoryFormRef.value) return
  
  await categoryFormRef.value.validate((valid) => {
    if (valid) {
      saveOrUpdateCategory(form)
        .then(() => {
          ElMessage.success('保存成功')
          goBack()
        })
        .catch(() => {
          ElMessage.error('保存失败')
        })
    }
  })
}

// 返回上一页
const goBack = () => {
  router.push('/articles/categories')
}

// 初始化
onMounted(() => {
  // 判断是否为编辑模式
  if (route.params.id) {
    isEdit.value = true
    getCategoryDetail(route.params.id)
  }
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}
</style>